import mqtt from 'mqtt'
import config from '@/config'
import store from '@/store'

/** 移纤业务执行进度 */
const TRANSFER_PROCESS = 'vrich/iot/transfer/process'

/** OTDR测试业务执行进度 */
const OTDR_TEST_PROCESS = 'vrich/iot/otdrTest/process'

/** OTDR测试结果 */
const OTDR_TEST_RESULT = 'vrich/iot/otdrTest/result'

/** 光纤拔插进度 */
const UNPLUG_PROCESS = 'vrich/iot/unplug/process'

/** 任务进度 */
const TASK_PROCESS = 'vrich/oen/task/process'

/** 告警新增 */
const ALARM_ADD = 'vrich/biz/alarm/add'

/** 告警结束 */
const ALARM_OVER = 'vrich/biz/alarm/over'

/** 系统通知 */
const SYS_NOTICE = 'vrich/biz/sys/notice'

/** MQTT连接信息 */
const { service, username, password, keepalive } = config.mqtt

/** MQTT客户端 */
const client = mqtt.connect(service, { username, password, keepalive })

/** 建立连接后订阅Topic */
client.on('connect', () => {
  console.log('mqtt订阅成功')
  client.subscribe(
    [
      'vrich/iot/transfer/process',
      'vrich/iot/otdrTest/process',
      'vrich/iot/otdrTest/result',
      'vrich/iot/unplug/process',
      'vrich/oen/task/process',
      'vrich/biz/alarm/add',
      'vrich/biz/alarm/over',
      'vrich/biz/sys/notice'
    ]
  )
})

/** 收到消息后进行消息分发到Store */
client.on('message', (topic, message) => {
  try {
    const data = JSON.parse(message.toString())
    switch (topic) {
      case TRANSFER_PROCESS:
        console.log(topic + ' ==> ' + message.toString())
        store.commit('setTransferProcess', data)
        break
      case OTDR_TEST_PROCESS:
        console.log(topic + ' ==> ' + message.toString())
        store.commit('setOtdrTestProcess', data)
        break
      case OTDR_TEST_RESULT:
        console.log(topic + ' ==> ' + message.toString())
        store.commit('setOtdrTestResult', data)
        break
      case UNPLUG_PROCESS:
        console.log(topic + ' ==> ' + message.toString())
        store.commit('setUnplugProcess', data)
        break
      case ALARM_ADD:
        console.log(topic + ' ==> ' + message.toString())
        store.commit('SETALARM_ADD', data)
        break
      case ALARM_OVER:
        console.log(topic + ' ==> ' + message.toString())
        store.commit('ALARM_REMOVE', data)
        store.commit('REMOVE_NOTIFY_LIST', data)
        store.commit('REMOVE_MARQUEEN_LIST', data)
        break
      case TASK_PROCESS:
        console.log(topic + ' ==> ' + message.toString())
        store.commit('setTaskProcess', data)
        break
      case SYS_NOTICE:
        store.commit('addSysNoticeCount')
        break
      default:
        break
    }
  } catch (error) {
    console.log(error)
  }
})

export default client
